package com.czk.gulimall.sso.client.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/3/7 22:09
 */
@Controller
public class HelloController {
    @Value("${sso.server.url}")
    private String ssoServerUrl;

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    /**
     * 登陆成功带回来的token
     * @param model
     * @param session
     * @param token 登陆成功带回来的token
     * @return
     */
    @GetMapping("/employee")
    public String employee(Model model, HttpSession session,@RequestParam(value = "token",required = false) String token) {
        if (!StringUtils.isEmpty(token)){
            // 去sso服务器获取真正的对应用户信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> entity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            String body = entity.getBody();
            session.setAttribute("loginUser",body);
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            // 没登录
            // 跳转到登录服务器
            return "redirect:" + ssoServerUrl+"?redirect_url=http://client1.com:8081/employee";
        }
        List<String> list = new ArrayList<>();
        list.add("czk");
        list.add("czj");
        model.addAttribute("emps", list);
        return "list";
    }
}
